package com.example.springboottestgit.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.springboottestgit.bean.BusinessException;
import com.example.springboottestgit.bean.InviteTenderFileUploadRecord;
import com.example.springboottestgit.bean.SubmitTenderFileUploadRecord;
import com.example.springboottestgit.bean.vo.OutputVO;
import com.example.springboottestgit.dao.InviteTenderFileUploadRecordMapper;
import com.example.springboottestgit.dao.SubmitTenderFileUploadRecordMapper;
import com.example.springboottestgit.enums.ExceptionCodeEnum;
import com.example.springboottestgit.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: ZZZ
 */
@Slf4j
@Service
public class ExeScriptServer {

    @Value("${tender.exe.url}")
    private String tenderExeUrl;

    @Value("${invite.business.exe.url}")
    private String inviteBusinessUrl;

    @Value("${invite.technology.exe.url}")
    private String inviteTechnologyUrl;

    @Value("${submit.business.exe.url}")
    private String submitBusinessUrl;

    @Value("${submit.technology.exe.url}")
    private String submitTechnologyUrl;


    @Autowired
    private SubmitTenderFileUploadRecordMapper submitTenderFileUploadRecordMapper;
    @Autowired
    private InviteTenderFileUploadRecordMapper inviteTenderFileUploadRecordMapper;

    //@Async("myAsync")
    public String exeScript(long id, String filepath, String fileName, int fileType, int exeType, String businessTenderTxtPath, String technologyTxtPath) {
        String url = tenderExeUrl;
        // 0：单个文件  1：商务文件 2：技术文件 3：价格文件

        if (exeType == 0) {
            if (fileType == 1) {
                url = inviteBusinessUrl;
            } else {
                url = inviteTechnologyUrl;
            }

        } else {
            if (fileType == 1) {
                url = submitBusinessUrl;
            } else {
                url = submitTechnologyUrl;
            }
        }


        File file = new File(filepath);
        Map<String, Object> map = new HashMap<>();
        map.put("filePath", filepath);
        map.put("fileType", fileType);
        map.put("exeType", exeType);
        map.put("fileName", fileName);
        map.put("file", file);
        String exeResult = null;
        log.info("招投标文件解析接口请求参数 ：" + JSONObject.toJSONString(map));
        try {
            //result = HttpUtil.createPost(url).header("Content-Type", "application/json").body(param).execute().body();
            exeResult = HttpUtil.createPost(url)
                    .header("Content-Type", "multipart/form-data")
                    .form(map)
                    .execute()
                    .body();


            OutputVO outputVO = JSONObject.parseObject(exeResult, OutputVO.class);
            if ("000000".equals(outputVO.getCode())) {
                analysisResultSave(fileType, businessTenderTxtPath, technologyTxtPath, outputVO);
                updateFileStatus(id, exeType, 1);
                log.info("招标文件解析成功,返回结果：{}", exeResult);
            } else {
                log.error("招标文件解析失败,返回结果：{}", exeResult);
                throw new BusinessException(ExceptionCodeEnum.BUSINESS_ERROR.code, "招标文件解析失败");
            }


        } catch (Exception e) {
            log.error("招投标文件解析接口调用失败", e);
            updateFileStatus(id, exeType, 2);
            throw new BusinessException(ExceptionCodeEnum.INTERFACE_CALL_FAIL.code, "招投标文件解析接口调用");
        }
        return exeResult;

    }


    public void updateFileStatus(long id, int exeType, int status) {
        //更新文件状态
        //exeType 0-招标 1-投标
        if (exeType == 0) {
            InviteTenderFileUploadRecord update = new InviteTenderFileUploadRecord();
            update.setId(id);
            update.setStatus(status);
            inviteTenderFileUploadRecordMapper.updateById(update);

        } else {
            SubmitTenderFileUploadRecord update = new SubmitTenderFileUploadRecord();
            update.setId(id);
            update.setStatus(status);
            submitTenderFileUploadRecordMapper.updateById(update);

        }

    }


    public void analysisResultSave(Integer fileType, String businessTxtPath, String technologyTxtPath, OutputVO outputVO) {

        if (fileType == 0) {
            if (!StringUtils.hasText(outputVO.getData().getBusinessContent())) {
                outputVO.getData().setBusinessContent(outputVO.getData().getInitContent());
            }

            FileUtil.txtWriterAppend(businessTxtPath, outputVO.getData().getBusinessContent());
            FileUtil.txtWriterAppend(technologyTxtPath, outputVO.getData().getTechnologyContent());
        }

        if (fileType == 1 || fileType == 3) {
            //businessContent  空取 initContent
            if (!StringUtils.hasText(outputVO.getData().getBusinessContent())) {
                outputVO.getData().setBusinessContent(outputVO.getData().getInitContent());
            }
            FileUtil.txtWriterAppend(businessTxtPath, outputVO.getData().getBusinessContent());
        }

        if (fileType == 2) {
            //technologyContent 空取 initContent
            if (!StringUtils.hasText(outputVO.getData().getTechnologyContent())) {
                outputVO.getData().setTechnologyContent(outputVO.getData().getInitContent());
            }
            FileUtil.txtWriterAppend(technologyTxtPath, outputVO.getData().getTechnologyContent());
        }
    }


}
